# target
TARGET=nano

BUILD_DIR=build

# wch risc gcc12
CROSS_COMPILE=riscv-wch-elf-
CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
LD=$(CROSS_COMPILE)ld
DP=$(CROSS_COMPILE)objdump

# SRC 
SRC_C=src/main.c src/interrupt.c src/led.c 
SRC_S=src/startup_ch32v30x_D8C.S

SRC_LD=Link.ld

OBJC=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJS=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_S:.S=.o)))

INC=-Isrc -I.

#CFLAGS
CFLAGS= \
-march=rv32imacxw \
-mabi=ilp32 \
-msmall-data-limit=8 -msave-restore -fmax-errors=20 -Os -fmessage-length=0 -fsigned-char \
-ffunction-sections -fdata-sections -Wunused -Wuninitialized \
-g3

CFLAGS+= \
--specs=nano.specs \
--specs=nosys.specs    

LIBS=\
-lm
#如果程序并不实际使用系统函数，但是某些代码引用了系统函数，那么可以引入libnosys，以便通过编译。
#LIBS+=-lnosys

# LD FLAGS
LDFLAGS= $(CFLAGS) \
-nostartfiles -Xlinker --gc-sections -Xlinker --print-memory-usage -Wl,-Map,"$(TARGET).map" 

LDFLAGS+=-T$(SRC_LD) $(LIBS)

LDFLAGS += -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref
 

#SET PATH %.c %.S
vpath %.c $(sort $(dir $(SRC_C)))
vpath %.S $(sort $(dir $(SRC_S)))

ELF=$(BUILD_DIR)/$(TARGET).elf
BIN=$(BUILD_DIR)/$(TARGET).bin
DIS=$(BUILD_DIR)/$(TARGET).dis 

.PHONY : all clean d c download

all: $(BUILD_DIR) $(BIN) $(DIS)

$(BUILD_DIR):
	mkdir $@

# cc .c
$(BUILD_DIR)/%.o:%.c 
	@echo .CC $<
	@$(CC) $(CFLAGS) -c $< $(INC) -o $@

# as .S
$(BUILD_DIR)/%.o:%.S 
	@echo .AS $<
	@$(AS) $(CFLAGS) -c $< $(INC) -o $@

# elf
$(ELF):$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo link elf $@
	@$(CC) $(OBJC) $(OBJS) $(LDFLAGS)  -o $@
	@$(SZ) $@ 

#cp .bin
$(BIN):$(ELF)
	@echo objcopy bin
	$(CP) -O binary -S $< $@


$(DIS):$(ELF)
	@echo objdump dis
	@$(DP) -D -h -s $< > $@

clean:
	rm -rf $(BUILD_DIR)

d:
	make clean
	make all

c:$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo .o

download:
	../../tools/wch_openocd/bin/openocd \
	-s ../../tools/wch_openocd/bin/ \
	-f wch-riscv.cfg \
	-c "program build/nano.elf verify reset" \
	-c "reset run" \
	-c exit
# -f target/gd32e23x.cfg \